/**
 * Created by ding on 2017/8/4.
 */
var fileUrl;
var gMap;
var maintenanceStatus = 3;
$.getActorId = function (data) {
    if (data.indexOf("7") >= 0) {
        actorId = 7;
    }
    if (data.indexOf("5") >= 0) {
        actorId = 5;
    }
    if (data.indexOf("1") >= 0) {
        actorId = 1;
    }
    return actorId;
};

var actorId = $.getActorId(gUserLoginResult.userActors);

$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_signalLampHandle/getSignalLampFaultHandle4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTables').DataTable().search(this.value);
                d.orgId = gUserLoginResult.orgId;
                d.actorIds = gUserLoginResult.userActors;
                d.lampMaintenanceStatus = maintenanceStatus;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: "signalLampPhoto",
            render: function (data, type, row) {
                var pic = "../images/default_photo.png";
                if (data.length != 0)
                    pic = data;
                return "<img src='" + pic + "' style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + pic + "\")'> ";
            }
        }, {
            data: "lampPhoto",
            render: function (data, type, row) {
                var pic = "../images/default_photo.png";
                if (data.length != 0)
                    pic = data;
                return "<img src='" + pic + "' style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + pic + "\")'> ";
            }
        }, {
            data: null,
            render: function (data, type, row) {
                return row.signalLampProvince + " " + row.signalLampCity + " " + row.signalLampArea;
            }
        }, {
            data: "lampType",
            render: function (data, type, row) {
                var machineType = "正常";
                switch (data) {
                    case 0:
                        machineType = "损毁";
                        break;
                    case 1:
                        machineType = "其他";
                        break;
                    default:
                        machineType = "未知";
                        break;
                }
                return machineType;
            }
        }, {
            data: "lampLevel",
            render: function (data, type, row) {
                var machineLevel = "无";
                switch (data) {
                    case 1:
                        machineLevel = "一级";
                        break;
                    case 2:
                        machineLevel = "二级";
                        break;
                    case 3:
                        machineLevel = "三级";
                        break;
                    case 4:
                        machineLevel = "四级";
                        break;
                    case 5:
                        machineLevel = "五级";
                        break;
                }
                return machineLevel;
            }
        }, {
            data: "lampMaintenanceStatus",
            render: function (data, type, row) {
                var lampMaintenanceStatus = "";
                switch (data) {
                    case 1:
                        lampMaintenanceStatus = "待维修";
                        break;
                    case 2:
                        lampMaintenanceStatus = "维修完成";
                        break;
                    default:
                        lampMaintenanceStatus = "其他";
                        break;
                }
                return lampMaintenanceStatus;
            }
        }, {
            data: "lampMaintainerName",
            render: function (data, type, row) {
                if (data == null)
                    return "待维修";
                else
                    return data;
            }
        }, {
            data: "lampMainCheckTime",
            render: function (data, type, row) {
                return data.substring(0, 10);
            }
        }, {
            data: "lampMaintenanceStatus",
            render: function (data, type, row) {
                var buttonOperation = "";
                var buttonUpdate;
                switch (data) {
                    case 1:
                        if (row.lampMaintenanceContent != "" && row.lampMaintenanceContent != null) {
                            buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' " +
                                "onclick='$.updateMaintenanceModal(" + JSON.stringify(row) + ")' title='编辑'>" +
                                "<i class='fa fa-wrench'></i></button>";
                        }
                        else
                            buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' " +
                                "onclick='$.supplyMaintenanceModal(" + JSON.stringify(row) + ")' title='完善'>" +
                                "<i class='fa fa-edit'></i></button>";
                        break;
                    case 2:
                        buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' " +
                            "onclick='$.showMaintenanceModal(" + JSON.stringify(row) + ")' title='查看'>" +
                            "<i class='fa fa-id-card'></i></button>";
                        break;
                }
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonUpdate + " ";
                buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' " +
                "data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
                "<span class='caret'></span><span class='sr-only'>切换下拉</span></button>" +
                "<ul class='dropdown-menu'>" +
                "<li>" +
                "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>" +
                "</li>";

            var maintenanceStatusBar = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.switchMaintenanceStatus(1)'><i class='fa fa-battery-half'></i>待维修</button></li>";
            maintenanceStatusBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.switchMaintenanceStatus(2)'><i class='fa fa-battery-full'></i> 维修完成</button></li>";
            maintenanceStatusBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.switchMaintenanceStatus(3)'><i class='fa fa-square'></i> 全部</button></li>";
            strToolBar += maintenanceStatusBar;

            strToolBar += "</ul></div> " +
                "<div class='input-group input-group-sm'>" +
                "<input type='text' class='form-control' id='searchText' placeholder='路名'>" +
                "<span class='input-group-btn'>" +
                "<button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'>" +
                "<i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    $('#maintenanceTimeUpdate').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayBtn: 'linked',
        language: 'zh-CN'
    });

    if (actorId == 7) {
        var oTable = $('#mainDataTables').dataTable();
        oTable.fnSetColumnVis(9, false);//隐藏列
    }

});

$.fn.searchDT = function () {
    gMainDT.search($("#searchText").val()).draw();
};

$.switchMaintenanceStatus = function (status) {
    maintenanceStatus = status;
    gMainDT.ajax.reload(null, false);
};

$.supplyMaintenanceModal = function (jsonData) {
    $("#maintenanceIdSupply").val(jsonData.lampFaultId);
    $("#maintenanceReasonSupply").val(jsonData.lampReason);
    $("#maintenanceFeedbackSupply").val(jsonData.lampFeedback);
    $("#supplyMaintenanceLabel").text("添加施工方案");
    $("#supplyMaintenanceModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

function myDateFormat(s) {
    return s < 10 ? '0' + s : s;
}

//完成施工Modal
$.updateMaintenanceModal = function (jsonData) {
    $.getSolarMaintainer(jsonData.lampOrgId);
    gMap = 1;
    var myDate = new Date();
    var date = myDate.getFullYear() + "-" + myDateFormat(myDate.getMonth() + 1) + "-" + myDateFormat(myDate.getDate());
    $("#maintenanceIdUpdate").val(jsonData.lampFaultId);
    $("#provinceUpdate").val(jsonData.signalLampProvince);
    $("#cityUpdate").val(jsonData.signalLampCity);
    $("#areaUpdate").val(jsonData.signalLampArea);
    $("#coordinate").val(jsonData.signalLampLongitude + "," + jsonData.signalLampLatitude);
    // $("#roadNameUpdate").val(jsonData.solarEnergyRoadName);
    $("#startRoadUpdate").val(jsonData.signalLampStartRoad);
    $("#endRoadUpdate").val(jsonData.signalLampEndRoad);
    $("#maintenancePic").attr("src", "../images/default_photo.png");
    $("#maintenanceSelect").val(-1);
    $("#maintenanceReasonUpdate").val(jsonData.lampReason);
    $("#maintenanceTimeUpdate").val(date);
    $("#maintenanceContentUpdate").val(jsonData.lampMaintenanceContent);
    $("#updateMaintenanceLabel").text("完成施工");
    $("#updateMaintenanceModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};


// 打开上传modal框
$.openUpPic = function () {
    $("#upPictureModal").modal({
        backdrop: 'static',
        keyboard: true,
        show: true
    });
};

// 关闭上传modal框
$.closeUpPhModal = function () {
    $("#upPictureModal").modal("hide");
    $("#ossfile").empty();
    clearOssData();
};

//获取图片信息
$.doneUpPhoto = function () {
    var fileInfo = getOssFileInfo();
    fileUrl = fileInfo[0].fileUrl;
    $("#maintenancePic").attr("src", fileUrl);
    $.closeUpPhModal();
};

//判断文件类型(在需要的js文件添加，文件名务必保持一致)
function judgeFileType(suffix) {
    //图片文件
    if (!(suffix == ".jpg" || suffix == ".JPG" || suffix == ".png" || suffix == ".PNG" ||
            suffix == ".jpeg" || suffix == ".JPEG" || suffix == ".gif" || suffix == ".GIF" ||
            suffix == ".bmp" || suffix == ".BMP")) {
        alert("请选择图片文件！");
        return false;
    }
}


$(".myBtnUpdate").click(function () {
    //coordinate4Show
    var coordinate;
    if (gMap == 1) {
        coordinate = $("#coordinate").val().split(",");
    }
    else {
        coordinate = $("#coordinate4Show").val().split(",");
    }
    var url = "fault/roadPoleAuditMap.html";
    url += "?x=" + coordinate[0] + "&y=" + coordinate[1] + "&z=1";//通过这种方式传参数
    $("#myMap").attr("src", url);
    $("#modal-map").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
});

//维修记录Modal
$.showMaintenanceModal = function (jsonData) {
    gMap = 2;
    $("#provinceShow").val(jsonData.signalLampProvince);
    $("#cityShow").val(jsonData.signalLampCity);
    $("#areaShow").val(jsonData.signalLampArea);
    $("#coordinate4Show").val(jsonData.signalLampLongitude + "," + jsonData.signalLampLatitude);
    $("#startRoadShow").val(jsonData.signalLampStartRoad);
    $("#endRoadShow").val(jsonData.signalLampEndRoad);
    $("#maintenanceReasonShow").val(jsonData.lampReason);
    $("#maintenanceContentShow").val(jsonData.lampMaintenanceContent);
    $("#maintenancePicShow").attr("src", jsonData.lampMaintenancePhoto);
    $("#maintenanceLevelShow").val(jsonData.lampLevel);
    $("#maintenanceTypeShow").val(jsonData.lampType)
    $("#maintenanceExplainShow").val(jsonData.lampMaintenanceExplain);
    $("#maintenancePeopleShow").val(jsonData.lampMaintainerName)
    $("#showMaintenanceLabel").text("维修记录");
    $.setPdfInfo(jsonData);
    
    $("#showMaintenanceModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};


/*打印按钮实现*/
$("#pdf-btn").click(function () {
    $("#maintenancePdf").jqprint({
        debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
        importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
        printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
        operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true

    });
})

$.setPdfInfo = function (jsonData) {
    $("#reporter").html(jsonData.lampCreatorName);
    $("#reportTime").html(jsonData.lampTime);
    $("#machinePosition").html(jsonData.signalLampProvince +
        " " + jsonData.signalLampCity + " " + jsonData.signalLampArea +
        " " + jsonData.signalLampStartRoad +
        "(起）-- " + jsonData.signalLampEndRoad + "(止)");
    $("#faultPic").attr("src", jsonData.lampPhoto);
    $("#okPic").attr("src", jsonData.lampMaintenancePhoto);
    $("#faultInfo").html(jsonData.lampReason);
    $("#faultType").html(jsonData.lampType == 0 ? "损坏" : "其他");
    var level = "";
    switch (jsonData.lampLevel) {
        case 0:
            level = "无";
            break;
        case 1:
            level = "一级";
            break;
        case 2:
            level = "二级";
            break;
        case 3:
            level = "三级";
            break;
        case 4:
            level = "四级";
            break;
        case 5:
            level = "五级";
            break;
    }
    $("#faultLevel").html(level);
    $("#endTime").html(jsonData.lampMaintenanceTime);
    $("#spendMoney").html(jsonData.lampMoney + "元");
    $("#remarks").html(jsonData.lampMaintenanceExplain);
};

$('#supplyMaintenanceForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        maintenanceContent: {
            validators: {
                notEmpty: {
                    /*非空提示*/
                    message: '请输入施工方案'
                },
                stringLength: {max: 200, message: '施工方案长度不超过200'},
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var $form = $(e.target);
    $.ajax({
        url: "../rds_signalLampHandle/addLampMaintenanceContent",
        type: 'post',
        data: {
            lampFaultId: $("#maintenanceIdSupply").val(),
            lampMaintenanceContent: $("#maintenanceContentSupply").val()
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    $.alert("数据操作成功", 1);
                    gMainDT.ajax.reload(null, false);
                } else {
                    $.alert("数据操作失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
    $.clearModal($("#supplyMaintenanceForm"), $("#supplyMaintenanceModal"))
});
//
$('#updateMaintenanceForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        maintenanceSignStatus: {
            validators: {
                notEmpty: {message: '标志分类不能为空'}
            }
        },
        maintenanceExplain: {
            validators: {
                stringLength: {max: 200, message: '施工说明长度不超过200'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    $("#maintenancePicUpdate").val(fileUrl);
    var $form = $(e.target);
    if ($("#maintenanceSelect").val() == -1) {
        $.alert("请选择维修人员", 2)
    } else if ($("#maintenanceTimeUpdate").val() == "") {
        $.alert("请选择维修日期", 2)
    } else if ($("#maintenancePic").attr('src') == "../images/default_photo.png") {
        $.alert("请上传完工图片", 2)
    } else if ($("#maintenanceExplainUpdate").val() == "") {
        $.alert("请填写施工说明", 2)
    } else {
        $.ajax({
            url: "../rds_signalLampHandle/finishLampMaintenance",
            type: 'post',
            data: {
                lampMaintenancePhoto: $("#maintenancePic").attr('src'),
                lampFaultId: $("#maintenanceIdUpdate").val(),
                lampMaintainerId: $("#maintenanceSelect").val(),
                lampMaintenanceTime: $("#maintenanceTimeUpdate").val(),
                lampMaintenanceExplain: $("#maintenanceExplainUpdate").val()
            },
            dataType: 'json',
            success: function (msg) {
                if (msg != null && typeof (msg) != "undefined") {
                    if (msg.isSuccess == true) {
                        $.alert("数据操作成功", 1);
                        gMainDT.ajax.reload(null, false);
                        $.clearModal($("#updateMaintenanceForm"), $("#updateMaintenanceModal"))
                    } else {
                        $.alert("数据操作失败", 2);
                    }
                } else {
                    $.alert('系统错误，请联系管理员', 2);
                }
            },
            error: function () {
                $.alert('系统错误，请联系管理员', 2);
            }
        });
    }
});

$.getSolarMaintainer = function (data) {
    $.ajax({
        url: "../rds_solarEnergyHandle/getSolarMaintainer",
        type: 'post',
        data: {
            solarOrgId: data
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    $("#maintenanceSelect").empty();
                    $("#maintenanceSelect").append("<option value='-1'>可选维修人员</option>");
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        $("#maintenanceSelect").append("<option value='" + msg.jsonData[i].userId + "'>" + msg.jsonData[i].userName + "</option>");
                    }
                } else {
                    $.alert("数据操作失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
}

$("#maintenancePicShow").click(function () {
    $.showPicModal($(this).attr("src"));
});
